package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.oss.enumd.OssBucketOneEnum;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.*;
import cn.cdeden.knowledge.domain.dto.EnterpriseTemplateTreeQueryParam;
import cn.cdeden.knowledge.domain.dto.FileTemplateTreeDto;
import cn.cdeden.knowledge.domain.dto.TemplateTreeQueryParam;
import cn.cdeden.knowledge.domain.vo.FilesSizeType;
import cn.cdeden.knowledge.enums.FileSuffixTypeEnum;
import cn.cdeden.knowledge.enums.StorageTypeEnum;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.mapper.*;
import cn.cdeden.knowledge.service.PersonalFilesTreeService;
import cn.cdeden.knowledge.utils.FileUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.resource.api.RemoteFileService;
import cn.cdeden.resource.api.RemoteOssEsService;
import cn.cdeden.resource.api.domain.RemoteEsFilesTree;
import cn.cdeden.resource.api.domain.RemoteFile;
import cn.cdeden.resource.api.domain.RemoteFileDto;
import cn.cdeden.system.api.RemoteDeptService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteDeptVo;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import io.undertow.util.BadRequestException;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cdeden.knowledge.service.FileTemplateTreeService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FileTemplateTreeServiceImpl extends ServiceImpl<FileTemplateTreeMapper, FileTemplateTree> implements FileTemplateTreeService{

    private final FileTemplateTreeMapper fileTemplateTreeMapper;

    private final TemplateCollectionsMapper templateCollectionsMapper;

    private final PersonalFilesTreeMapper personalFilesTreeMapper;

    private final PersonalFilesTreeService personalFilesTreeService;

    private final EnterpriseFilesTreeMapper enterpriseFilesTreeMapper;

    @DubboReference(check = false)
    private final RemoteOssEsService remoteOssEsService;

    @DubboReference(check = false)
    private final RemoteFileService remoteFileService;

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;

    @DubboReference(check = false)
    private final RemoteDeptService remoteDeptService;

    private final TeamFilesTreeMapper teamFilesTreeMapper;

    private final PersonalFilesTreeService filesTreeService;


    @Override
    public TableDataInfo<Template> queryTemplate(TemplateTreeQueryParam query, Pageable pageable) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        IPage<FileTemplateTree> queryPage = PageUtil.toMybatisPage(pageable);

        if (TreeEnum.PERSONAL.getType().equals(query.getState())) {
            query.setCreateId(user.getUserId());
        } else if (TreeEnum.ENTERPRISE.getType().equals(query.getState())) {

        }else if ("community".equals(query.getState())){

        }else {

        }

        QueryWrapper<EnterpriseTemplateTreeQueryParam> predicate = QueryHelpMybatisPlus.getPredicate(query);
        if (TreeEnum.ENTERPRISE.getType().equals(query.getState())){
//            RemoteDeptVo byId = remoteDeptService.getById(user.getDeptId());
//            DeptDto convert = MapstructUtils.convert(byId, DeptDto.class);
//            ArrayList<Dept> depts = new ArrayList<>();
            List<RemoteDeptVo> superiors = remoteDeptService.getSuperiorAll(user.getDeptId());
            List<Long> collect = superiors.stream().map(RemoteDeptVo::getDeptId).collect(Collectors.toList());
            TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), EnterpriseTemplateTreeQueryParam.class);
            predicate.lambda().and(consumer -> {
                consumer.in(EnterpriseTemplateTreeQueryParam::getDeptId, collect).or().isNull(EnterpriseTemplateTreeQueryParam::getDeptId);
            });
        }
        IPage<Template> page = fileTemplateTreeMapper.queryTemplate(queryPage, predicate, user.getUserId());
        return TableDataInfo.build(page);
    }

    @Override
    public List<FileTemplateTree> queryHotName(Integer size) {
//        List<FileTemplateTree> list = fileTemplateTreeMapper.lambdaQuery().orderByDesc(FileTemplateTree::getPreview).list();
        List<FileTemplateTree> list = fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>().orderByDesc(FileTemplateTree::getPreview));
        return list;
    }

    @Override
    public TableDataInfo<Template> queryCollectionTemplate(TemplateTreeQueryParam query, Pageable pageable) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        IPage<Template> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<Template> page = fileTemplateTreeMapper.queryCollectionTemplate(queryPage, query.getType(),query.getRealName(), user.getUserId());
        return TableDataInfo.build(page);
    }

    @Override
    public List<FileTemplateTree> getTemplateFile(List<Long> treeNodeIds) {
        return fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>().in(FileTemplateTree::getId, treeNodeIds));
    }

    @Override
    public boolean uploadTemplateToCommon(FileTemplateTree fileTemplateTree) {
        LoginUser user = LoginHelper.getLoginUser();

        FileTemplateTree templateTree = fileTemplateTreeMapper.selectById(fileTemplateTree.getId());

        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(templateTree.getStorageId()));
        RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), OssModuleType.Template);

        FileTemplateTree newFileTemplateTree = new FileTemplateTree();
        newFileTemplateTree.setParentId(fileTemplateTree.getParentId());
        newFileTemplateTree.setRealName(fileTemplateTree.getRealName());
        //判断是否重命名
        List<FileTemplateTree> fileTemplateTrees = fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>()
            .isNull(FileTemplateTree::getDeleteId).eq(FileTemplateTree::getParentId, fileTemplateTree.getParentId()));
        List<String> realNames = fileTemplateTrees
            .stream()
            .filter(v -> v.getDeleteId() == null || ! v.getDeleteId().equals("1"))
            .map(v -> v.getRealName() + "." + v.getSuffix())
            .collect(Collectors.toList());
        if (realNames.contains(fileTemplateTree.getRealName() + "." + newRemoteFile.getFileSuffix())) {
            newFileTemplateTree.setRealName(fileTemplateTree.getRealName() + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        }


        newFileTemplateTree.setSuffix(newRemoteFile.getFileSuffix());
        newFileTemplateTree.setType(FileSuffixTypeEnum.fromExtension(newFileTemplateTree.getSuffix()).name());
        newFileTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        newFileTemplateTree.setStorageType("minio");
        newFileTemplateTree.setState(fileTemplateTree.getState());
        newFileTemplateTree.setCreateId(user.getUserId().toString());
        newFileTemplateTree.setCreateBy(user.getUsername());
        newFileTemplateTree.setCreateTime(new Date());
        newFileTemplateTree.setLibraryType("template");
        int insert = fileTemplateTreeMapper.insert(newFileTemplateTree);

        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public void isAddCollection(Long templateId, Boolean isAdd) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        UpdateWrapper<FileTemplateTree> wrapper = new UpdateWrapper<>();
        TemplateCollections templateCollections = new TemplateCollections();
        templateCollections.setTemplateId(templateId);
        templateCollections.setUserId(user.getUserId());
        if (isAdd) {
            //添加到模板的点赞
            wrapper.setSql("collection=collection+1").eq("id", templateId);
            //添加到点赞表
            templateCollectionsMapper.insert(templateCollections);
        } else {
            QueryWrapper<TemplateCollections> wrapper1 = new QueryWrapper<>();
            TemplateCollections templateCollections1 = new TemplateCollections();
            templateCollections1.setTemplateId(templateId);
            templateCollections1.setUserId(user.getUserId());
            wrapper1.setEntity(templateCollections1);
            //删除到模板的点赞
            wrapper.setSql("collection=collection-1").eq("id", templateId);
            //删除点赞表
            templateCollectionsMapper.delete(wrapper1);
        }
        update(wrapper);
    }

    @Override
    public void removePersonalTemplate(Long id) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        FileTemplateTreeDto byId = findById(id);
        if (byId!=null&&byId.getState().equals(TreeEnum.PERSONAL.getType())&&byId.getCreateId().equals(user.getUserId().toString())){
            //TODO 删除minio服务器中的文件方法待确认
            removeTemplate(byId);
        } else {
            throw new BadRequestException("传递参数值错误");
        }
    }

    @Override
    public FileTemplateTreeDto findById(Long id) {
        return MapstructUtils.convert(getById(id), FileTemplateTreeDto.class);
    }

    @Override
    public boolean uploadPersonalTemplate(FileTemplateTree fileTemplateTree) {
        PersonalFilesTree personalFilesTree = personalFilesTreeMapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, fileTemplateTree.getId()));

        LoginUser user = LoginHelper.getLoginUser();
        //复制文件到模版桶中
        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(personalFilesTree.getStorageId()));
        RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), OssModuleType.Template);


        FileTemplateTree newFileTemplateTree = new FileTemplateTree();
        newFileTemplateTree.setParentId(fileTemplateTree.getParentId());
        newFileTemplateTree.setRealName(fileTemplateTree.getRealName());

        //判断文件重命名
        List<FileTemplateTree> fileTemplateTrees = fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>()
            .isNull(FileTemplateTree::getParentId)
            .isNull(FileTemplateTree::getDeleteId)
            .eq(FileTemplateTree::getState, "personal")
            .eq(FileTemplateTree::getCreateId, user.getUserId().toString()));
        List<String> realNames = fileTemplateTrees
            .stream()
            .filter(v -> v.getDeleteId() == null || ! v.getDeleteId().equals("1"))
            .map(v -> v.getRealName() + "." + v.getSuffix())
            .collect(Collectors.toList());
        if (realNames.contains(fileTemplateTree.getRealName() + "." + newRemoteFile.getFileSuffix())) {
            newFileTemplateTree.setRealName(fileTemplateTree.getRealName() + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        }

        newFileTemplateTree.setSuffix(newRemoteFile.getFileSuffix());
        newFileTemplateTree.setType(FileSuffixTypeEnum.fromExtension(newFileTemplateTree.getSuffix()).name());
        newFileTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        newFileTemplateTree.setStorageType("minio");
        newFileTemplateTree.setState(fileTemplateTree.getState());
        newFileTemplateTree.setCreateId(user.getUserId().toString());
        newFileTemplateTree.setCreateBy(user.getUsername());
        newFileTemplateTree.setCreateTime(new Date());
        newFileTemplateTree.setLibraryType("template");
        int insert = fileTemplateTreeMapper.insert(newFileTemplateTree);






//        //存入信息
//        FileTemplateTree fileTemplateTree1 = new FileTemplateTree();
//        fileTemplateTree1.setId(null);
//        fileTemplateTree1.setParentId(null);
//        fileTemplateTree1.setSuffix(personalFilesTree.getSuffix());
//        fileTemplateTree1.setRealName(personalFilesTree.getRealName());
//        fileTemplateTree1.setType("");
//        //**********
//        fileTemplateTree1.setStorageId(personalFilesTree.getStorageId());
//        //************
//        fileTemplateTree1.setStorageType("minio");
//        fileTemplateTree1.setState(fileTemplateTree.getState());
//        fileTemplateTree1.setCreateId(user.getUserId().toString());
//        fileTemplateTree1.setCreateBy(user.getUsername());
//        fileTemplateTree1.setCreateTime(new Date());
//        fileTemplateTree1.setLibraryType("template");
//
//        //数据存入
//        int insert = fileTemplateTreeMapper.insert(fileTemplateTree1);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean uploadEnterpriseTemplate(FileTemplateTree fileTemplateTree) {
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectOne(new LambdaQueryWrapper<EnterpriseFilesTree>().eq(EnterpriseFilesTree::getId, fileTemplateTree.getId()));
        LoginUser user = LoginHelper.getLoginUser();

        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(enterpriseFilesTree.getStorageId()));
        RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), null);

        FileTemplateTree newFileTemplateTree = new FileTemplateTree();
        newFileTemplateTree.setParentId(fileTemplateTree.getParentId());
        newFileTemplateTree.setRealName(fileTemplateTree.getRealName());
        newFileTemplateTree.setSuffix(newRemoteFile.getFileSuffix());
        newFileTemplateTree.setType(FileSuffixTypeEnum.fromExtension(newFileTemplateTree.getSuffix()).name());
        newFileTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        newFileTemplateTree.setStorageType("minio");
        newFileTemplateTree.setState(fileTemplateTree.getState());
        newFileTemplateTree.setCreateId(user.getUserId().toString());
        newFileTemplateTree.setCreateBy(user.getUsername());
        newFileTemplateTree.setCreateTime(new Date());
        newFileTemplateTree.setLibraryType("template");
        int insert = fileTemplateTreeMapper.insert(newFileTemplateTree);




//        //存入信息
//        FileTemplateTree fileTemplateTree1 = new FileTemplateTree();
//        fileTemplateTree1.setId(null);
//        fileTemplateTree1.setParentId(null);
//        fileTemplateTree1.setSuffix(personalFilesTree.getSuffix());
//        fileTemplateTree1.setRealName(personalFilesTree.getRealName());
//        fileTemplateTree1.setType("");
//        //**********
//        fileTemplateTree1.setStorageId(personalFilesTree.getStorageId());
//        //************
//        fileTemplateTree1.setStorageType("minio");
//        fileTemplateTree1.setState(fileTemplateTree.getState());
//        fileTemplateTree1.setCreateId(user.getUserId().toString());
//        fileTemplateTree1.setCreateBy(user.getUsername());
//        fileTemplateTree1.setCreateTime(new Date());
//        fileTemplateTree1.setLibraryType("template");
//
//        //数据存入
//        int insert = fileTemplateTreeMapper.insert(fileTemplateTree1);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean uploadPersonalTemplateToCommon(FileTemplateTree fileTemplateTree) {
        PersonalFilesTree personalFilesTree = personalFilesTreeMapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, fileTemplateTree.getId()));
        LoginUser user = LoginHelper.getLoginUser();
        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(personalFilesTree.getStorageId()));
        //复制文件信息
        RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), OssModuleType.Template);

        FileTemplateTree newFileTemplateTree = new FileTemplateTree();
        newFileTemplateTree.setParentId(fileTemplateTree.getParentId());
        newFileTemplateTree.setRealName(fileTemplateTree.getRealName());

        //判断文件重命名
        List<FileTemplateTree> fileTemplateTrees = fileTemplateTreeMapper.selectList(new LambdaQueryWrapper<FileTemplateTree>()
            .isNull(FileTemplateTree::getDeleteId)
            .eq(FileTemplateTree::getParentId, fileTemplateTree.getParentId()));
        List<String> realNames = fileTemplateTrees
            .stream()
            .filter(v -> v.getDeleteId() == null || ! v.getDeleteId().equals("1"))
            .map(v -> v.getRealName() + "." + v.getSuffix())
            .collect(Collectors.toList());
        if (realNames.contains(fileTemplateTree.getRealName() + "." + newRemoteFile.getFileSuffix())) {
            newFileTemplateTree.setRealName(fileTemplateTree.getRealName() + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        }

        newFileTemplateTree.setSuffix(newRemoteFile.getFileSuffix());
        newFileTemplateTree.setType(FileSuffixTypeEnum.fromExtension(newFileTemplateTree.getSuffix()).name());
        newFileTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        newFileTemplateTree.setStorageType("minio");
        newFileTemplateTree.setState(fileTemplateTree.getState());
        newFileTemplateTree.setCreateId(user.getUserId().toString());
        newFileTemplateTree.setCreateBy(user.getUsername());
        newFileTemplateTree.setCreateTime(new Date());
        newFileTemplateTree.setLibraryType("template");
        int insert = fileTemplateTreeMapper.insert(newFileTemplateTree);


//
//
//
//
//
//        //存入信息
//        FileTemplateTree fileTemplateTree1 = new FileTemplateTree();
//        fileTemplateTree1.setId(null);
//        fileTemplateTree1.setParentId(null);
//        fileTemplateTree1.setSuffix(personalFilesTree.getSuffix());
//        fileTemplateTree1.setRealName(personalFilesTree.getRealName());
//        fileTemplateTree1.setType("");
//        //**********
//        fileTemplateTree1.setStorageId(personalFilesTree.getStorageId());
//        //************
//        fileTemplateTree1.setStorageType("minio");
//        fileTemplateTree1.setState(fileTemplateTree.getState());
//        fileTemplateTree1.setCreateId(user.getUserId().toString());
//        fileTemplateTree1.setCreateBy(user.getUsername());
//        fileTemplateTree1.setCreateTime(new Date());
//        fileTemplateTree1.setLibraryType("template");
//
//        //数据存入
//        int insert = fileTemplateTreeMapper.insert(fileTemplateTree1);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean uploadEnterpriseTemplateToCommon(FileTemplateTree fileTemplateTree) {
        EnterpriseFilesTree personalFilesTree = enterpriseFilesTreeMapper.selectOne(new LambdaQueryWrapper<EnterpriseFilesTree>().eq(EnterpriseFilesTree::getId, fileTemplateTree.getId()));
        LoginUser user = LoginHelper.getLoginUser();
        //复制文件
        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(personalFilesTree.getStorageId()));
        RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), OssModuleType.Template);


        FileTemplateTree newFileTemplateTree = new FileTemplateTree();
        newFileTemplateTree.setParentId(fileTemplateTree.getParentId());
        newFileTemplateTree.setRealName(fileTemplateTree.getRealName());
        newFileTemplateTree.setSuffix(newRemoteFile.getFileSuffix());
        newFileTemplateTree.setType(FileSuffixTypeEnum.fromExtension(newFileTemplateTree.getSuffix()).name());
        newFileTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        newFileTemplateTree.setStorageType("minio");
        newFileTemplateTree.setState(fileTemplateTree.getState());
        newFileTemplateTree.setCreateId(user.getUserId().toString());
        newFileTemplateTree.setCreateBy(user.getUsername());
        newFileTemplateTree.setCreateTime(new Date());
        newFileTemplateTree.setLibraryType("template");
        int insert = fileTemplateTreeMapper.insert(newFileTemplateTree);

//        //存入信息
//        FileTemplateTree fileTemplateTree1 = new FileTemplateTree();
//        fileTemplateTree1.setId(null);
//        fileTemplateTree1.setParentId(null);
//        fileTemplateTree1.setSuffix(personalFilesTree.getSuffix());
//        fileTemplateTree1.setRealName(personalFilesTree.getRealName());
//        fileTemplateTree1.setType("");
//        //**********
//        fileTemplateTree1.setStorageId(personalFilesTree.getStorageId());
//        //************
//        fileTemplateTree1.setStorageType("minio");
//        fileTemplateTree1.setState(fileTemplateTree.getState());
//        fileTemplateTree1.setCreateId(user.getUserId().toString());
//        fileTemplateTree1.setCreateBy(user.getUsername());
//        fileTemplateTree1.setCreateTime(new Date());
//        fileTemplateTree1.setLibraryType("template");
//
//        //数据存入
//        int insert = fileTemplateTreeMapper.insert(fileTemplateTree1);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public FileTemplateTreeDto useTemplate(FileTemplateTreeDto fileTemplateTreeDto) throws IOException {
        LoginUser user = LoginHelper.getLoginUser();
        RemoteUserVo remoteUserVo = remoteUserService.selectUserByUserId(user.getUserId());

        //查询模版文件中的StorageId
        FileTemplateTree fileTemplateTree = fileTemplateTreeMapper.selectOne(new LambdaQueryWrapper<FileTemplateTree>().eq(FileTemplateTree::getId, fileTemplateTreeDto.getId()));

        //判断复制到那个模块当中
        if (fileTemplateTreeDto.getUseType().equals("personal") && !fileTemplateTreeDto.getCreateType().equals("new")) {

            RemoteFile remoteFile = new RemoteFile();
            remoteFile.setOssId(Long.valueOf(fileTemplateTree.getStorageId()));
            //根据ParentId查询出上级文件夹的信息，用于处理新文件的路径相关的信息
            String parentId = fileTemplateTreeDto.getParentId();
            PersonalFilesTree newPersonalFilesTree = personalFilesTreeMapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, Long.valueOf(fileTemplateTreeDto.getParentId())));
            //复制
            RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, remoteUserVo.getMinioBucket(), OssModuleType.Template);
            PersonalFilesTree personalFilesTree = new PersonalFilesTree();
            personalFilesTree.setTopParentId(newPersonalFilesTree.getTopParentId());
            personalFilesTree.setParentId(fileTemplateTreeDto.getParentId());
            //根据不同的情况设置父级路径
            if (newPersonalFilesTree.getSuperiorsIds() != null) {
                personalFilesTree.setSuperiorsIds(newPersonalFilesTree.getSuperiorsIds() + "," + fileTemplateTreeDto.getParentId());
            }
            if (newPersonalFilesTree.getSuperiorsIds() == null) {
                personalFilesTree.setSuperiorsIds(fileTemplateTreeDto.getParentId());
            }
            personalFilesTree.setSuffix(newRemoteFile.getFileSuffix());
            //判断是否有重名的文件
            personalFilesTree.setRealName(fileTemplateTreeDto.getRealName());
            List<PersonalFilesTree> personalFilesTrees = personalFilesTreeService.selectByParentIdAll(fileTemplateTreeDto.getParentId());
            List<String> realNames = personalFilesTrees
                .stream()
                .filter(v -> v.getDeleteId() == null || ! v.getDeleteId().equals("1"))
                .map(v -> v.getRealName() + "." + v.getSuffix())
                .collect(Collectors.toList());
            if (realNames.contains(fileTemplateTreeDto.getRealName() + "." + newRemoteFile.getFileSuffix())) {
                personalFilesTree.setRealName(personalFilesTree.getRealName() + "_" + "模版文件" + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            }

            personalFilesTree.setSuperiorsPath(newPersonalFilesTree.getPath());
            personalFilesTree.setPath(personalFilesTree.getSuperiorsPath() + "/" + personalFilesTree.getRealName());
            personalFilesTree.setType("file");
            personalFilesTree.setStorageId(newRemoteFile.getOssId().toString());
            personalFilesTree.setStorageType("minio");
            personalFilesTree.setSize(newRemoteFile.getFileSize());
            personalFilesTree.setEdition(newRemoteFile.getVersionId());
            personalFilesTree.setEditionName(newRemoteFile.getVersionName());
            personalFilesTree.setCreateId(remoteUserVo.getUserId().toString());
            personalFilesTree.setCreateBy(remoteUserVo.getUserName());
            personalFilesTree.setCreateTime(new Date());
            personalFilesTree.setUpdateId(remoteUserVo.getUserId().toString());
            personalFilesTree.setUpdateBy(remoteUserVo.getUserName());
            personalFilesTree.setUpdateTime(new Date());
            //存储数据
            personalFilesTreeMapper.insert(personalFilesTree);

            //修改所有上级文件夹的大小
            personalFilesTreeService.upDateFolderSize(personalFilesTree, FilesSizeType.AddSize);

            //新增es数据
            RemoteEsFilesTree remoteEsFilesTree = new RemoteEsFilesTree();
            remoteEsFilesTree.setId(personalFilesTree.getId());
            remoteEsFilesTree.setLibraryType(OssModuleType.Personal.getCode());
            remoteEsFilesTree.setVersionId(personalFilesTree.getEdition());
            remoteEsFilesTree.setVersionName(personalFilesTree.getEditionName());
            remoteEsFilesTree.setSuffix(personalFilesTree.getSuffix());
            remoteEsFilesTree.setType(personalFilesTree.getType());
            remoteEsFilesTree.setStorageId(personalFilesTree.getStorageId());
            remoteEsFilesTree.setSize(personalFilesTree.getSize());
            remoteEsFilesTree.setCreateBy(remoteUserVo.getUserId());
            remoteEsFilesTree.setCreateTime(personalFilesTree.getCreateTime());
            remoteEsFilesTree.setUpdateBy(remoteUserVo.getUserId());
            remoteEsFilesTree.setUpdateTime(personalFilesTree.getUpdateTime());
            remoteEsFilesTree.setRealName(personalFilesTree.getRealName());
            remoteEsFilesTree.setParentId(personalFilesTree.getParentId());
            remoteEsFilesTree.setUserIdList(Arrays.asList(remoteUserVo.getUserId().toString()));

            //修改个人文件中的esId
            try {
                String insert = remoteOssEsService.insert(remoteEsFilesTree);
                PersonalFilesTree personalFilesTreeUpdate = new PersonalFilesTree();
                personalFilesTreeUpdate.setId(personalFilesTree.getId());
                personalFilesTreeUpdate.setEsId(insert);
                personalFilesTreeService.updateById(personalFilesTreeUpdate);
            }catch (Exception e) {

            }


            FileTemplateTreeDto fileTemplateTreeDto1 = new FileTemplateTreeDto();
            fileTemplateTreeDto1.setId(personalFilesTree.getId());
            fileTemplateTreeDto1.setLibraryType("personal");
            return fileTemplateTreeDto1;
        }

        //判断是否为新建文件
        if (fileTemplateTreeDto.getUseType().equals("personal") && fileTemplateTreeDto.getCreateType().equals("new")) {
            // 创建Base64文件流
            String fileBase64 = createEmptyFile(fileTemplateTreeDto.getType());
            String fileSuffix = null;
            if (fileTemplateTreeDto.getType().equals("word")) {
                fileSuffix = "docx";
            }

            if (fileTemplateTreeDto.getType().equals("excel")) {
                fileSuffix = "xlsx";
            }

            if (fileTemplateTreeDto.getType().equals("ppt")) {
                fileSuffix = "pptx";
            }


            // 将Base64字符串转换为byte[]
            byte[] fileBytes = Base64.getDecoder().decode(fileBase64);

            RemoteFileDto remoteFileDto = RemoteFileDto.builder()
                .originalFilename(fileTemplateTreeDto.getRealName() + "." + fileSuffix)
                .contentType("file")
                .bucketName(remoteUserVo.getMinioBucket())
                .moduleType(OssModuleType.Personal)
                .file(fileBytes)
                .build();
            RemoteFile upload = remoteFileService.upload(remoteFileDto);
            //数据插入存入个人库中
            //根据ParentId查询出上级文件夹的信息，用于处理新文件的路径相关的信息
            PersonalFilesTree newPersonalFilesTree = personalFilesTreeMapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, Long.valueOf(fileTemplateTreeDto.getParentId())));
            PersonalFilesTree personalFilesTree = new PersonalFilesTree();
            personalFilesTree.setTopParentId(newPersonalFilesTree.getTopParentId());
            personalFilesTree.setParentId(fileTemplateTreeDto.getParentId());
            //根据不同的情况设置父级路径
            if (newPersonalFilesTree.getSuperiorsIds() != null) {
                personalFilesTree.setSuperiorsIds(newPersonalFilesTree.getSuperiorsIds() + "," + fileTemplateTreeDto.getParentId());
            }
            if (newPersonalFilesTree.getSuperiorsIds() == null) {
                personalFilesTree.setSuperiorsIds(fileTemplateTreeDto.getParentId());
            }
            personalFilesTree.setSuffix(upload.getFileSuffix());
            //判断是否有重名的文件
            personalFilesTree.setRealName(fileTemplateTreeDto.getRealName());
            List<PersonalFilesTree> personalFilesTrees = personalFilesTreeService.selectByParentIdAll(fileTemplateTreeDto.getParentId());
            List<String> realNames = personalFilesTrees
                .stream()
                .filter(v -> v.getDeleteId() == null || ! v.getDeleteId().equals("1"))
                .map(v -> v.getRealName() + "." + v.getSuffix())
                .collect(Collectors.toList());
            if (realNames.contains(fileTemplateTreeDto.getRealName() + "." + upload.getFileSuffix())) {
                personalFilesTree.setRealName(personalFilesTree.getRealName() + "_" + "模版文件" + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            }

            personalFilesTree.setSuperiorsPath(newPersonalFilesTree.getPath());
            personalFilesTree.setPath(personalFilesTree.getSuperiorsPath() + "/" + personalFilesTree.getRealName());
            personalFilesTree.setType("file");
            personalFilesTree.setStorageId(upload.getOssId().toString());
            personalFilesTree.setStorageType("minio");
            personalFilesTree.setSize(upload.getFileSize());
            personalFilesTree.setEdition(upload.getVersionId());
            personalFilesTree.setEditionName(upload.getVersionName());
            personalFilesTree.setCreateId(remoteUserVo.getUserId().toString());
            personalFilesTree.setCreateBy(remoteUserVo.getUserName());
            personalFilesTree.setCreateTime(new Date());
            personalFilesTree.setUpdateId(remoteUserVo.getUserId().toString());
            personalFilesTree.setUpdateBy(remoteUserVo.getUserName());
            personalFilesTree.setUpdateTime(new Date());
            //存储数据
            personalFilesTreeMapper.insert(personalFilesTree);

            //修改所有上级文件夹的大小
            personalFilesTreeService.upDateFolderSize(personalFilesTree, FilesSizeType.AddSize);

            //新增es数据
            RemoteEsFilesTree remoteEsFilesTree = new RemoteEsFilesTree();
            remoteEsFilesTree.setId(personalFilesTree.getId());
            remoteEsFilesTree.setLibraryType(OssModuleType.Personal.getCode());
            remoteEsFilesTree.setVersionId(personalFilesTree.getEdition());
            remoteEsFilesTree.setVersionName(personalFilesTree.getEditionName());
            remoteEsFilesTree.setSuffix(personalFilesTree.getSuffix());
            remoteEsFilesTree.setType(personalFilesTree.getType());
            remoteEsFilesTree.setStorageId(personalFilesTree.getStorageId());
            remoteEsFilesTree.setSize(personalFilesTree.getSize());
            remoteEsFilesTree.setCreateBy(remoteUserVo.getUserId());
            remoteEsFilesTree.setCreateTime(personalFilesTree.getCreateTime());
            remoteEsFilesTree.setUpdateBy(remoteUserVo.getUserId());
            remoteEsFilesTree.setUpdateTime(personalFilesTree.getUpdateTime());
            remoteEsFilesTree.setRealName(personalFilesTree.getRealName());
            remoteEsFilesTree.setParentId(personalFilesTree.getParentId());
            remoteEsFilesTree.setUserIdList(Arrays.asList(remoteUserVo.getUserId().toString()));

            try {
                String insert = remoteOssEsService.insert(remoteEsFilesTree);
                //修改个人文件中的esId
                PersonalFilesTree personalFilesTreeUpdate = new PersonalFilesTree();
                personalFilesTreeUpdate.setId(personalFilesTree.getId());
                personalFilesTreeUpdate.setEsId(insert);
                personalFilesTreeService.updateById(personalFilesTreeUpdate);
            } catch (Exception e) {

            }


            FileTemplateTreeDto fileTemplateTreeDto1 = new FileTemplateTreeDto();
            fileTemplateTreeDto1.setId(personalFilesTree.getId());
            fileTemplateTreeDto1.setLibraryType("personal");
            fileTemplateTreeDto1.setSuffix(personalFilesTree.getSuffix());
            fileTemplateTreeDto1.setType(personalFilesTree.getType());
            return fileTemplateTreeDto1;

        }
        return null;
    }

    public static String createEmptyFile(String type) throws IOException {
        byte[] fileBytes = null;

        switch (type.toLowerCase()) {
            case "word":
                // 创建一个空的Word文件
                fileBytes = createEmptyWordFile();
                break;
            case "ppt":
                // 创建一个空的PPT文件
                fileBytes = createEmptyPptFile();
                break;
            case "excel":
                // 创建一个空的Excel文件
                fileBytes = createEmptyExcelFile();
                break;
            default:
                throw new IllegalArgumentException("Unsupported file type: " + type);
        }

        // 将文件字节转换为Base64字符串
        return Base64.getEncoder().encodeToString(fileBytes);
    }

    private static byte[] createEmptyWordFile() throws IOException {
        // 创建一个空的Word文档
        XWPFDocument document = new XWPFDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        document.write(out);
        return out.toByteArray();
    }

    private static byte[] createEmptyPptFile() throws IOException {
        // 创建一个空的PPT文件
        XMLSlideShow ppt = new XMLSlideShow();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ppt.write(out);
        return out.toByteArray();
    }

    private static byte[] createEmptyExcelFile() throws IOException {
        // 创建一个空的Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet 1");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        return out.toByteArray();
    }


    /**
     * 公共删除方法
     */
    public void removeTemplate(FileTemplateTreeDto enterpriseTemplateTree) {

        //TODO 删除方法待确认
        String storageId = enterpriseTemplateTree.getStorageId();
        if (storageId != null){
            ArrayList<Long> strings = new ArrayList<>();
            strings.add(Long.valueOf(storageId));
            remoteFileService.deleteWithValidByIds(strings,false);
        }else {

        }
        removeById(enterpriseTemplateTree.getId());
    }


    /**
     * 对模板文件的编辑
     *
     * @param id
     * @param parentId
     * @param name
     */
    @Override
    public void updateTemplate(Long id, Long parentId, Long deptId, String name, MultipartFile file, MultipartFile image) {
        LoginUser user = LoginHelper.getLoginUser();
        FileTemplateTree byId = getById(id);
        if (id == null || StringUtils.isNullOrBlank(name) || parentId == null||byId==null)
            throw new RuntimeException("参数不能为空");
        FileTemplateTree enterpriseTemplateTree = new FileTemplateTree();
        String documentType = null;
        //上传文件
        if (file != null&&image != null){
            String filename = file.getOriginalFilename();
            documentType = FileUtil.getDocumentType(FileUtil.getExtensionName(filename));
            RemoteFileDto remoteFile = new RemoteFileDto();
            try {
                remoteFile.setFile(file.getBytes());
                remoteFile.setCoverFile(image.getBytes());
            }catch (IOException e){
                throw new RuntimeException("文件上传失败");
            }

            remoteFile.setContentType(file.getContentType());
            remoteFile.setBucketName(OssBucketOneEnum.TEMPLATE_BUCKET.getCode());
            remoteFile.setCoverContentType(image.getContentType());
            remoteFile.setCoverSuffix(FileUtil.getSuffix(image.getOriginalFilename()));
            RemoteFile newRemoteFile = remoteFileService.upload(remoteFile);
            enterpriseTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        } else if (file != null) {
            String filename = file.getOriginalFilename();
            documentType = FileUtil.getDocumentType(FileUtil.getExtensionName(filename));
            RemoteFileDto remoteFile = new RemoteFileDto();
            try {
                remoteFile.setFile(file.getBytes());
            }catch (IOException e){
                throw new RuntimeException("文件上传失败");
            }
            remoteFile.setOriginalFilename(file.getOriginalFilename());
            remoteFile.setModuleType(OssModuleType.Template);
            remoteFile.setContentType(file.getContentType());
            remoteFile.setBucketName(OssBucketOneEnum.TEMPLATE_BUCKET.getCode());
            RemoteFile newRemoteFile = remoteFileService.upload(remoteFile);
//            Storage storage = fileStorageUtils.create(user.getId().toString(), user.getUsername(), StorageFolderTypeEnum.TEMPLATE_BUCKET.getCode(), file, FileEnums.ENTERPRISE_TEMPLATE, null);
            enterpriseTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        } else if (image != null) {
            documentType = byId.getType();
//            fileStorageUtils.uploadThumbnail(byId.getStorageId(),image);
            try {
                remoteFileService.uploadCoverImage(image.getBytes(),image.getContentType(),FileUtil.getSuffix(image.getOriginalFilename()),byId.getStorageId());
            }catch (Exception e){
                throw new RuntimeException("封面上传失败");
            }

        }else {
            documentType = byId.getType();
        }
        enterpriseTemplateTree.setId(id);
        enterpriseTemplateTree.setParentId(Long.valueOf(parentId.toString()));
        enterpriseTemplateTree.setType(documentType);
        enterpriseTemplateTree.setRealName(getRealName(id,name,documentType,TreeEnum.ENTERPRISE.getType(),parentId.toString()));
        enterpriseTemplateTree.setDeptId(deptId);
        baseMapper.updateById(enterpriseTemplateTree);
    }

    /**
     * 批量上传
     * @param parentId
     * @param files
     */
    @Override
    public void uploadTemplateAdmin(Long parentId, List<MultipartFile> files, Long deptId){
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (parentId == null){
            throw new RuntimeException("分类为空");
        }
        if (files == null || files.size() == 0){
            throw new RuntimeException("上传文件为空");
        }
        for (MultipartFile file : files) {
            FileTemplateTree enterpriseTemplateTree = new FileTemplateTree();
            String filename = file.getOriginalFilename();
            String extensionName = FileUtil.getExtensionName(filename);
            String realName = FileUtil.getFileNameNoEx(filename);
            String documentType = FileUtil.getDocumentType(extensionName);
            if (documentType == null){
                continue;
            }
            String realName1 = getRealName(null,realName, documentType, TreeEnum.ENTERPRISE.getType(), parentId.toString());
//            Storage storage = fileStorageUtils.create(user.getId().toString(), user.getUsername(), StorageFolderTypeEnum.TEMPLATE_BUCKET.getCode(), file, FileEnums.ENTERPRISE_TEMPLATE, null);
            RemoteFileDto remoteFile = new RemoteFileDto();
            try {
                remoteFile.setFile(file.getBytes());
            }catch (IOException e){
                throw new RuntimeException("文件上传失败");
            }

            remoteFile.setContentType(file.getContentType());
            remoteFile.setModuleType(OssModuleType.Template);
            remoteFile.setOriginalFilename(file.getOriginalFilename());
            remoteFile.setBucketName(OssBucketOneEnum.TEMPLATE_BUCKET.getCode());
            RemoteFile newRemoteFile = remoteFileService.upload(remoteFile);

            enterpriseTemplateTree.setState(TreeEnum.ENTERPRISE.getType());
            enterpriseTemplateTree.setSuffix(extensionName);
            enterpriseTemplateTree.setParentId(parentId);
            enterpriseTemplateTree.setType(documentType);
            enterpriseTemplateTree.setRealName(realName1);
            enterpriseTemplateTree.setDeptId(deptId);
            enterpriseTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
            enterpriseTemplateTree.setCreateId(loginUser.getUserId().toString());
            enterpriseTemplateTree.setCreateBy(loginUser.getUsername());
            enterpriseTemplateTree.setStorageType(StorageTypeEnum.MINIO.getType());
            enterpriseTemplateTree.setCreateTime(new Date());
            enterpriseTemplateTree.setLibraryType(TreeTypeEnum.TEMPLATE.getType());
            save(enterpriseTemplateTree);
        }
    }

    /**
     * 对模板文件的新增
     *
     * @param parentId
     * @param name
     * @param file
     * @param image
     */
    @Override
    public void uploadTemplateAdmin(Long parentId, Long deptId, String name, MultipartFile file, MultipartFile image) {
//        FileUserDto user = FileUserUtils.getUser();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if ( StringUtils.isNullOrBlank(name) || parentId == null)
            throw new RuntimeException("参数不能为空");
        if (file == null)throw new RuntimeException("必须上传文件");
        String filename = file.getOriginalFilename();
        String documentType = FileUtil.getDocumentType(FileUtil.getExtensionName(filename));
        if (documentType==null)throw new RuntimeException("文档类型有误");
        FileTemplateTree enterpriseTemplateTree = new FileTemplateTree();
        enterpriseTemplateTree.setParentId(parentId);
        enterpriseTemplateTree.setRealName(getRealName(null,name,documentType,TreeEnum.ENTERPRISE.getType(),parentId.toString()));
        enterpriseTemplateTree.setDeptId(deptId);
        enterpriseTemplateTree.setType(documentType);
        enterpriseTemplateTree.setSuffix(FileUtil.getExtensionName(filename));
        enterpriseTemplateTree.setState(TreeEnum.ENTERPRISE.getType());
        enterpriseTemplateTree.setStorageType(StorageTypeEnum.MINIO.getType());
        enterpriseTemplateTree.setLibraryType(TreeTypeEnum.TEMPLATE.getType());
        enterpriseTemplateTree.setCreateTime(new Date());
        enterpriseTemplateTree.setCreateId(loginUser.getUserId().toString());
        enterpriseTemplateTree.setCreateBy(loginUser.getUsername());
        //上传文件
        RemoteFileDto remoteFile = new RemoteFileDto();
        if (image != null){
            try {
                remoteFile.setCoverFile(image.getBytes());
                remoteFile.setCoverSuffix(FileUtil.getSuffix(image.getOriginalFilename()));
                remoteFile.setCoverContentType(image.getContentType());
            }catch (Exception e){
                throw new RuntimeException("封面上传失败");
            }
        }
        try {
            remoteFile.setFile(file.getBytes());
        }catch (IOException e){
            throw new RuntimeException("文件上传失败");
        }

        remoteFile.setContentType(file.getContentType());
        remoteFile.setBucketName(OssBucketOneEnum.TEMPLATE_BUCKET.getCode());
        remoteFile.setOriginalFilename(file.getOriginalFilename());
        remoteFile.setModuleType(OssModuleType.Template);
        RemoteFile newRemoteFile = remoteFileService.upload(remoteFile);
        enterpriseTemplateTree.setStorageId(newRemoteFile.getOssId().toString());
        save(enterpriseTemplateTree);
    }


    /**
     * 个人/团队转入模板中心
     *
     * @param id         文件id
     * @param type       个人还是团队请求
     * @param state      私人还是企业
     * @param classifyId 分类id
     * @return
     */
    @Override
    public FileTemplateTreeDto createTemplateCenter(Long id, String realName, String type, String state, String classifyId) {
        if (StringUtils.isNullOrBlank(type) || StringUtils.isNullOrBlank(realName)) {
            throw new RuntimeException("传递参数type或realName或classifyId为null");
        }
        if (id == null) throw new RuntimeException("传递参数id为null");
//        FileUserDto user = FileUserUtils.getUser();
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        String suffix = null;
        String storageId = null;
        String folderType = null;
        //团队还是个人文件
        if (TreeEnum.TEAM.getType().equals(type)) {
            TeamFilesTree byId = teamFilesTreeMapper.selectById(id);
            suffix = byId.getSuffix();
            storageId = byId.getStorageId();

            folderType = FileUtil.getDocumentType(suffix);
            } else if (TreeEnum.PERSONAL.getType().equals(type)) {
                PersonalFilesTree byId = filesTreeService.getById(id);
                suffix = byId.getSuffix();
                storageId = byId.getStorageId();
                folderType = FileUtil.getDocumentType(suffix);
            } else {
            throw new RuntimeException("错误请求参数type");
        }
        FileTemplateTreeDto enterpriseTemplateTreeDto = new FileTemplateTreeDto();
        //文件类型
        String documentType = FileUtil.getDocumentType(suffix);
        //if (isExistRealName(realName,documentType,TreeEnum.ENTERPRISE.getType(),))throw new BadRequestException("模板名称重复")
        enterpriseTemplateTreeDto.setRealName(realName)
            .setState(state)
            .setSuffix(suffix)
            .setType(folderType)
            .setCreateId(loginUser.getUserId().toString())
            .setCreateBy(loginUser.getUsername())
            .setCreateTime(new Date())
            .setLibraryType(TreeTypeEnum.TEMPLATE.getType())
            .setCreateId(userId.toString());
        if (documentType != null) {
            //执行文档保存
            RemoteFile remoteFile = new RemoteFile();
            remoteFile.setOssId(Long.valueOf(storageId));
            RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.TEMPLATE_BUCKET.getCode(), OssModuleType.Template);

            Long copyStorageId = newRemoteFile.getOssId();
            enterpriseTemplateTreeDto.setStorageId(copyStorageId.toString()).setStorageType(StorageTypeEnum.MINIO.getType());
        } else {
            throw new RuntimeException("错误文件类型");
        }
        if (isExistRealName(null,realName,documentType,state,classifyId))throw new RuntimeException("存在相同模板名称");
        //私人还是企业模板库
        if (TreeEnum.PERSONAL.getType().equals(state)) {
//            enterpriseTemplateTreeDto.setDeleteType("1");
            insertDto(enterpriseTemplateTreeDto);
        } else if (TreeEnum.ENTERPRISE.getType().equals(state)) {
            if (StringUtils.isNullOrBlank(classifyId))throw new RuntimeException("分类id为空");
            enterpriseTemplateTreeDto.setParentId(classifyId);
            //TODO:进入流程
//            enterpriseTemplateTreeDto.setDeleteType("0");
            insertDto(enterpriseTemplateTreeDto);
        } else {
            throw new RuntimeException("错误请求参数state");
        }
        return enterpriseTemplateTreeDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertDto(FileTemplateTreeDto dto) {
        FileTemplateTree convert = MapstructUtils.convert(dto, FileTemplateTree.class);
        int insert = fileTemplateTreeMapper.insert(convert);
        dto.setId(convert.getId());
        return insert;
    }

    /**
     * 根据重名校验，得到名称
     * count 传0
     */
    public String getRealName(Long id,String realName,String type,String state,String parentId){
        if (isExistRealName(id,realName,type,state,parentId)){
            return realName+"_"+System.currentTimeMillis();
        } else {
            return realName;
        }
    }

    public Boolean isExistRealName(Long id,String realName,String type,String state,String parentId){
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<FileTemplateTree> enterpriseTemplateTrees = new ArrayList<FileTemplateTree>();
        if (state.equals(TreeEnum.ENTERPRISE.getType())){
            enterpriseTemplateTrees = fileTemplateTreeMapper.lambdaQuery().eq(FileTemplateTree::getParentId,parentId).eq(FileTemplateTree::getState, TreeEnum.ENTERPRISE.getType()).eq(FileTemplateTree::getType, type).eq(FileTemplateTree::getRealName, realName).list();
        }else if (state.equals(TreeEnum.PERSONAL.getType())){
            enterpriseTemplateTrees = fileTemplateTreeMapper.lambdaQuery().eq(FileTemplateTree::getCreateId,loginUser.getUserId()).eq(FileTemplateTree::getState, TreeEnum.PERSONAL.getType()).eq(FileTemplateTree::getType, type).eq(FileTemplateTree::getRealName, realName).list();
        }else if (state.equals("community")){
            enterpriseTemplateTrees = fileTemplateTreeMapper.lambdaQuery().eq(FileTemplateTree::getState, "community").eq(FileTemplateTree::getType, type).eq(FileTemplateTree::getParentId,parentId).eq(FileTemplateTree::getRealName, realName).list();
        }else {
            return false;
        }
        if (id == null){
            if (enterpriseTemplateTrees.size() > 0)return true;
            else return false;
        }else {
            if (enterpriseTemplateTrees.size() > 0){
                FileTemplateTree fileTemplateTree = enterpriseTemplateTrees.get(0);
                if (fileTemplateTree.getId().equals(id)) return false;
                else return true;
            }
            else return false;
        }
    }

    /**
     * 后台查询公共模板库
     *
     * @return
     */
    @Override
    public TableDataInfo<Template> queryEnterpriseTemplate(String type, String realName, Long parentId, Pageable pageable){
        EnterpriseTemplateTreeQueryParam treeQueryParam = new EnterpriseTemplateTreeQueryParam();
        IPage<FileTemplateTree> queryPage = PageUtil.toMybatisPage(pageable);
        LoginUser loginUser = LoginHelper.getLoginUser();
        treeQueryParam.setState(TreeEnum.ENTERPRISE.getType());
        treeQueryParam.setParentId(parentId);
        treeQueryParam.setRealName(realName);
        treeQueryParam.setType(type);
        QueryWrapper<EnterpriseTemplateTreeQueryParam> predicate = QueryHelpMybatisPlus.getPredicate(treeQueryParam);
        IPage<Template> page = fileTemplateTreeMapper.queryTemplate(queryPage, predicate, loginUser.getUserId());
        return TableDataInfo.build(page);
    }

    /**
     * 删除公共库模板
     */
    @Override
    public void removeEnterpriseTemplate(Long id){
        FileTemplateTreeDto byId = findById(id);
        if (byId!=null && byId.getState().equals(TreeEnum.ENTERPRISE.getType())){
            removeTemplate(byId);
        } else {
            throw new RuntimeException("传递参数值错误");
        }
    }

    /**
     * 我的模板上传
     */
    @Override
    public void createTemplate(MultipartFile image, MultipartFile file, String realName, String parentId, String state) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (file == null) {
            throw new RuntimeException("错误请求参数file，不能为null");
        }
        if (StringUtils.isNullOrBlank(realName)) {
            realName = FileUtil.getFileNameNoEx(file.getOriginalFilename());
        }
        String filename = file.getOriginalFilename();
        String extensionName = FileUtil.getExtensionName(filename);
        String documentType = FileUtil.getDocumentType(extensionName);
        if (documentType == null) {
            throw new RuntimeException("上传文件格式有误");
        }
        //校验名称
        if (isExistRealName(null,realName,documentType,state, parentId))
            throw new RuntimeException("存在相同模板文件名称");
        RemoteFileDto remoteFile = new RemoteFileDto();
        if (image!=null&&!image.isEmpty()) {
            try {
                remoteFile.setCoverFile(image.getBytes());
                remoteFile.setCoverSuffix(FileUtil.getSuffix(image.getOriginalFilename()));
                remoteFile.setCoverContentType(image.getContentType());
            } catch (Exception e) {
                throw new RuntimeException("封面上传失败");
            }
        }
        try {
            remoteFile.setFile(file.getBytes());
        }catch (IOException e){
            throw new RuntimeException("文件上传失败");
        }

        remoteFile.setContentType(file.getContentType());
        remoteFile.setBucketName(OssBucketOneEnum.TEMPLATE_BUCKET.getCode());
        remoteFile.setOriginalFilename(file.getOriginalFilename());
        remoteFile.setModuleType(OssModuleType.Template);
        RemoteFile newRemoteFile = remoteFileService.upload(remoteFile);

        FileTemplateTree templateTree = new FileTemplateTree();
        templateTree.setStorageId(String.valueOf(newRemoteFile.getOssId()))
            .setCreateId(loginUser.getUserId().toString())
            .setType(documentType)
            .setStorageType(StorageTypeEnum.MINIO.getType())
            .setSuffix(extensionName)
            .setLibraryType(TreeTypeEnum.TEMPLATE.getType())
            .setRealName(realName);
        if (state.equals("personal")){
            templateTree.setState(TreeEnum.PERSONAL.getType());
        }else {
            templateTree.setState("community");
            templateTree.setParentId(Long.valueOf(parentId));
        }


        fileTemplateTreeMapper.insert(templateTree);
    }

}
